package com.example.yls.demoa;

import android.Manifest;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by yls on 2018/12/5.
 */

public class WriteFragment extends Fragment implements View.OnClickListener {
    private EditText editTextTitle;
    private EditText editTextContent;
    private TextView textViewDate;
    private TextView textViewLocation;
    private MyDatabaseHelper myDatabaseHelper;
    private SQLiteDatabase database;
    private SimpleDateFormat sf;
    private LocationClient mLocationClient;
    private StringBuilder currentPosition;
     private Button btnSummit;
     private String title = "";
     private String content = "";
     private String date = "";
    private String location = "";
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mLocationClient = new LocationClient(MyApplication.getContext());
        mLocationClient.registerLocationListener(new MyLocationListener());
        View view = inflater.inflate(R.layout.write_fragment, container, false);
         myDatabaseHelper = new MyDatabaseHelper(MyApplication.getContext(), "DiaryDatabase", null, 2);
        initView(view);
        sf = new SimpleDateFormat("yyyy年MM月dd日hh时mm分ss秒");
        getLocationPermission();
        getAndShowDate();
        initEven();
        return view;
    }

    private void initEven() {
        btnSummit.setOnClickListener(this);


    }

    public void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
    }
    private void initView(View view) {
        editTextContent = view.findViewById(R.id.edit_content);
        editTextTitle = view.findViewById(R.id.edit_title);
        textViewDate = view.findViewById(R.id.text_date);
        textViewLocation = view.findViewById(R.id.text_location);
        btnSummit=view.findViewById(R.id.summit_button);
    }
    private void getLocationPermission() {
        List<String> permissionList = new ArrayList<>();
        if ((ContextCompat.checkSelfPermission(MainActivity.getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) !=
                PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if ((ContextCompat.checkSelfPermission(MainActivity.getActivity(), Manifest.permission.READ_PHONE_STATE)) !=
                PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.READ_PHONE_STATE);
        }
        if ((ContextCompat.checkSelfPermission(MainActivity.getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) !=
                PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(MainActivity.getActivity(), permissions, 1);
        } else {
            requestLoacation();
        }
    }

    public void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) {
                    for (int result : grantResults) {
                        if (result != PackageManager.PERMISSION_GRANTED) {
                            Toast.makeText(MainActivity.getActivity(), "必须同意所有的权限才可以", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                    requestLoacation();
                } else {
                    Toast.makeText(MainActivity.getActivity(), "发生未知错误", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }
    private void requestLoacation() {
        initLocation();
        mLocationClient.start();
    }
    private void getAndShowDate() {
        Date date = new Date();
        String dt = sf.format(date);
        textViewDate.setText(dt);
    }



    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        //  option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
        option.setIsNeedAddress(true);
        option.setScanSpan(1000);
        mLocationClient.setLocOption(option);
    }

    private void showLocation(String location) {
        textViewLocation.setText(location);
    }

    private void saveDate() {
        if (database == null) {
            createOrOpenDataBase();
        }
        getData();
        Log.e("frag",title+content+date+location);
       if (title!=""&&content!=""){
            ContentValues values=new ContentValues();
            values.put("title",title);
            values.put("content",content);
            values.put("date",date);
            values.put("location",location);
            database.insert("Diary",null,values);
            values.clear();
        }

    }



    public class MyLocationListener implements BDLocationListener {
        public void onReceiveLocation(BDLocation bdLocation) {
            currentPosition = new StringBuilder();
            currentPosition.append(bdLocation.getProvince()).append(" ");
            currentPosition.append(bdLocation.getCity()).append(" ");
            currentPosition.append(bdLocation.getDistrict()).append(" ");
            currentPosition.append(bdLocation.getStreet()).append(" ");
            if (bdLocation.getProvince() != null) {
                showLocation(currentPosition.toString());
                Toast.makeText(MyApplication.getContext(),currentPosition.toString(),Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     *数据库的操作
     */

    public void onClick(View view) {
           switch (view.getId()){
               case R.id.summit_button:
                  saveDate();
                   break;
               default:
                   break;
           }
    }
    public void getData() {
        title = editTextTitle.getText().toString();
        content = editTextContent.getText().toString();
        date = textViewDate.getText().toString();
        location = textViewLocation.getText().toString();

    }

    private void createOrOpenDataBase() {
        database = myDatabaseHelper.getWritableDatabase();

    }

}
